package com.zenithmind.user.config;

import com.zenithmind.user.pojo.domain.Role;
import com.zenithmind.user.pojo.domain.User;
import com.zenithmind.user.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 自定义UserDetailsService实现
 * 将现有的用户体系集成到Spring Security中
 */
@Service
@RequiredArgsConstructor
public class CustomUserDetailsService implements UserDetailsService {

    private final UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.getUserByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在: " + username);
        }
        
        // 获取用户角色
        Role role = Optional.ofNullable(userService.getUserById(user.getId()))
            .map(userVO -> userVO.getRole())
            .orElse(null);
            
        // 构建权限列表
        List<SimpleGrantedAuthority> authorities;
        if (role != null) {
            authorities = List.of(
                new SimpleGrantedAuthority("ROLE_" + role.getRoleCode())
            );
        } else {
            authorities = Collections.emptyList();
        }
        
        // 创建UserDetails对象
        return new org.springframework.security.core.userdetails.User(
            user.getUsername(),
            user.getPassword(),
            user.getStatus() == 1, // enabled
            true,   // accountNonExpired
            true,   // credentialsNonExpired
            true,   // accountNonLocked
            authorities
        );
    }
} 